﻿using ESPL.CodeGenerator.Web.Models;
using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ESPL.CodeGenerator.Domain;
using ESPL.CodeGenerator.Common.Structs;
using LinqToEdmx;
using LinqToEdmx.Model.Conceptual;
using ESPL.CodeGenerator.Common.Enums;
using ESPL.CodeGenerator.Common.ProjectBuilders;
using ESPL.CodeGenerator.Domain.Utilities;

namespace ESPL.CodeGenerator.Web.Controllers
{
    public class EasyCodesController : ApiController
    {
        public IHttpActionResult RequestBuild(IList<ProjectDetails> models)
        {
            //var directoryPath = "D:\\Temp\\Northwind.edmx";
            var directoryPath = "D:\\Temp\\";
            var projectBuilder = CodeGeneratorFactory.CreateInstance().CreateProjectBuilder(HelperClass.GetConfig(directoryPath, "Northwind.edmx"));
            var filePath = HelperClass.InitializeProjectTree(projectBuilder);

            
            return Ok(filePath);
        }
    }


    public class HelperClass
    {
        public static ApplicationConfiguration GetConfig(string filePath, string fileName)
        {
            var path = System.IO.Path.Combine(filePath, fileName);
            var edmx = Edmx.Load(path);
            var entityTypes = edmx.GetItems<EntityType>();

            return new ApplicationConfiguration()
            {
                CompanyNameAbbrevation = "ESPL",
                ApplicationName = "SampleApp",
                DestinationPath = HttpContext.Current.Server.MapPath("~/BuildRequests"),
                IncludeCommon = true,
                IncludeData = true,
                IncludeDataTransfer = true,
                IncludeDomain = true,
                IncludeMVC5 = true,
                IncludePresentation = true,
                EdmxFilePath = filePath,
                EdmxFileName = fileName,
                Entities = entityTypes,
                VisualStudioVersion = VisualStudioVersion.VS2013,
                ResourceFolderPath = HttpContext.Current.Server.MapPath("~/")
            };
        }

        public static string InitializeProjectTree(ICodeBuilder projectBuilder)
        {
            var output = string.Empty;
            foreach (var requestItem in projectBuilder.InitializeProjectTree())
            {
                output = string.Format("{0}\n{1}", output, requestItem.Output);
            }
            string directoryPath = HttpContext.Current.Server.MapPath("~/BuildRequests");
            var zipFileName = "SampleApp";
            ZipHelper.ZipFolder(string.Format("{0}\\{1}", directoryPath, zipFileName), directoryPath, string.Format("{0}.zip", zipFileName));

            return string.Format("/BuildRequests/{1}.zip", directoryPath, zipFileName);
        }
    }
}
